<template>
  <div class="app-container">
    <label class="title"
           style="font-size: 20px;color: rgba(0,0,0,.85);font-weight: 600;line-height: 32px">考生管理</label>
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="区县" prop="qy">
        <el-select v-model="queryParams.qy" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in qyList"
            :key="dict.n"
            :label="dict.n"
            :value="dict.v"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学校" prop="zxmc">
        <el-select v-model="queryParams.zxmc" placeholder="请选择" clearable filterable size="small">
          <el-option
            v-for="dict in zxmcList"
            :key="dict.zxmc"
            :label="dict.zxmc"
            :value="dict.zxmc">
            <span style="float: left">{{ dict.zxmc }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.zxdm }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="bjdm">
        <el-select v-model="queryParams.bjdm" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in bjdmList"
            :key="dict.bjdm"
            :label="dict.bjdm"
            :value="dict.bjdm"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="准考号" prop="zkh">
        <el-input
          v-model="queryParams.zkh"
          placeholder="请输入准考号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建档号" prop="jdh">
        <el-input
          v-model="queryParams.jdh"
          placeholder="请输入建档号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="qkzt">
        <el-select v-model="queryParams.qkzt" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in dict.type.qkzt"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:candidates:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:candidates:export']"
        >打印
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="candidateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ scope.$index + (queryParams.pageNo - 1) * queryParams.pageSize + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="区县名称" align="center" prop="qy">
        <template slot-scope="scope">
          {{ resultqymc(scope.row.qy) }}
        </template>
      </el-table-column>
      <el-table-column label="准考号" align="center" prop="zkh"/>
      <el-table-column label="建档号" align="center" prop="jdh"/>
      <el-table-column label="姓名" align="center" prop="name"/>
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.gender"/>
        </template>
      </el-table-column>
      <el-table-column label="中学代码" align="center" prop="zxdm"/>
      <el-table-column label="中学名称" align="center" prop="zxmc"/>
      <el-table-column label="班级代码" align="center" prop="bjdm"/>
      <el-table-column label="状态" align="center" prop="qkzt"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetail(scope.row)"
            v-hasPermi="['business:candidates:detail']"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:candidates:update']"
          >编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增、修改考生对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form :inline="true" ref="form" :model="form" :rules="rules" label-width="80px" :disabled="disabled">
        <el-collapse v-model="activeNames">
          <el-collapse-item title="考生信息" name="1">
            <table id="table">
              <tr>
                <td>
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.name" placeholder="请输入姓名"/>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item label="性别" prop="gender">
                    <el-select v-model="form.gender" placeholder="请选择" clearable size="small" class="selectWidth"
                               style="width: 180px;">
                      <el-option
                        v-for="dict in dict.type.sys_user_sex"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </td>
                <td rowspan="4" height="200px">
                  <el-input v-model="form.zp" style="display: none"/>
                  <el-form-item label="照片" prop="zp">
                    <el-upload action="#" :http-request="requestUpload" :show-file-list="false"
                               :before-upload="uploadZp">
                      <el-empty :image-size="70" description="点击上传照片" v-if="dialogImageUrl==null"></el-empty>
                      <el-image style="width: 160px; height: 200px" :src="dialogImageUrl"
                                v-if="dialogImageUrl!=null"></el-image>
                    </el-upload>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td>
                  <el-form-item label="准考号" prop="zkh">
                    <el-input v-model="form.zkh" placeholder="请输入准考号"
                              oninput="value=value.replace(/[^0-9.]/g,'')"/>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item label="建档号" prop="jdh">
                    <el-input v-model="form.jdh" placeholder="请输入建档号"
                              oninput="value=value.replace(/[^0-9.]/g,'')"/>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td>
                  <el-form-item label="中学名称" prop="zxmc">
                    <el-select v-model="form.zxmc" filterable placeholder="请选择" size="small"
                               @change="zxmcChange" style="width: 180px;">
                      <el-option
                        v-for="dict in zxmcList"
                        :key="dict.zxmc"
                        :label="dict.zxmc"
                        :value="dict.zxdm">
                        <span style="float: left">{{ dict.zxmc }}</span>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item label="班级代码" prop="bjdm">
                    <el-input v-model="form.bjdm" placeholder="请输入班级代码"/>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td>
                  <el-form-item label="区县" prop="qy">
                    <el-select v-model="form.qy" filterable placeholder="请选择" size="small"
                               class="selectWidth" style="width: 180px;">
                      <el-option
                        v-for="dict in qyList"
                        :key="dict.n"
                        :label="dict.n"
                        :value="dict.v"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item label="身份证" prop="sfzh">
                    <el-input v-model="form.sfzh" placeholder="请输入身份证"/>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td>
                  <el-form-item label="联系电话" prop="lxdh">
                    <el-input v-model="form.lxdh" placeholder="请输入联系电话"/>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item label="平时分" prop="usualResults">
                    <el-input-number v-model="form.usualResults" placeholder="请输入平时分" :min="0" :max="5"
                                     style="width: 180px;"/>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td>
                  <el-form-item label="状态" prop="qkzt">
                    <el-select v-model="form.qkzt" placeholder="请选择" clearable size="small">
                      <el-option
                        v-for="dict in dict.type.qkzt"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </td>
              </tr>
            </table>
          </el-collapse-item>
          <el-collapse-item name="3">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" style="width: 600px"/>
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
.selectWidth {
  width: 207.44px;
}

#table > tr > td > div {
  margin: 0px;
}
</style>
<script>
import {listSchool} from '@/api/business/school/school'

import {
  addCandidate,
  candidates,
  candidatesDetail,
  examProjectsList,
  schoolClass,
  updateCandidate
} from '@/api/business/candidate/candidate'

import {getSuZhouQuYu} from '@/api/area'

import {uploadPhoto} from '@/api/system/user'

export default {
  name: 'candidateList',
  dicts: ['sys_user_sex', 'yes_no_1_0', 'qkzt'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      selections: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考生表格数据
      candidateList: [],
      candidateList2: [],
      // 弹出层标题
      title: '',
      detailTitle: '',
      updateTitle: '',
      // 是否显示弹出层
      open: false,
      detailOpen: false,
      updateOpen: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        qy: null,
        zxmc: null,
        bjdm: null,
        zkh: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // qy: [
        //   { required: true, message: '区县不能为空', trigger: 'blur' }
        // ],
        zkh: [
          {required: true, message: '准考号不能为空', trigger: 'blur'}
        ],
        jdh: [
          {required: true, message: '建档号不能为空', trigger: 'blur'},
          {min: 6, message: '建档号最少6位', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '姓名不能为空', trigger: 'blur'}
        ],
        gender: [
          {required: true, message: '姓别不能为空', trigger: 'blur'}
        ],
        bjdm: [
          {required: true, message: '班级代码不能为空', trigger: 'blur'}
        ],
        zxmc: [
          {required: true, message: '中学名称不能为空', trigger: 'blur'}
        ],
        usualResults: [
          {required: true, message: '平时成绩不能为空', trigger: 'blur'}
        ],
        xctyxm1: [
          {required: true, message: '选测项1不能为空', trigger: 'blur'}
        ],
        xctyxm2: [
          {required: true, message: '选测项2不能为空', trigger: 'blur'}
        ]
      },
      zxmcList: [],
      bjdmList: [],
      qkztList: [],
      projectIdList: [],
      doUpload: '',
      qyList: [],
      //图片
      dialogImageUrl: null,
      imageFile: null,
      disabled: false,
      activeNames: ['1', '2', '3'],
      jsDisabled: false
    }
  },
  created() {
    this.getList()
    listSchool().then(response => {
      this.zxmcList = response.rows
    })
    schoolClass().then(response => {
      this.bjdmList = response.data
    })
    examProjectsList().then(response => {
      this.projectIdList = response.data
    })
    getSuZhouQuYu().then(response => {
      this.qyList = response.data
    })
  },
  methods: {
    /** 查询考生列表 */
    getList() {
      this.loading = true
      candidates(this.queryParams).then(response => {
        const records = response.data.records
        this.candidateList = records
        this.total = response.data.totalCount
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮
    cancel2() {
      this.detailOpen = false
      this.reset()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selections = selection.map(item => item)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.setCandidateList2(this.selections)
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        zkh: null,
        jdh: null,
        name: null,
        gender: null,
        zxdm: null,
        zxmc: null,
        bjdm: null,
        zp: null,
        bctyxm: '1000米/800米',
        xctyxm1: null,
        xctyxm2: null,
      }
      this.dialogImageUrl = null
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.reset()
      const id = row.id
      candidatesDetail(id).then(response => {
        this.form = response.data
        this.form.gender = response.data.gender + ''
        this.dialogImageUrl = response.data.zpStr
        this.form.qy = response.data.qy
        this.disabled = true
        this.open = true
        this.title = '修改考生'
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id
      candidatesDetail(id).then(response => {
        this.form = response.data
        this.form.gender = response.data.gender + ''
        this.dialogImageUrl = response.data.zpStr
        this.form.qy = response.data.qy
        this.form.qkzt = response.data.qkzt
        this.disabled = false
        this.open = true
        this.title = '修改考生'
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增考生'
      this.disabled = false
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.dialogImageUrl == null) {
            this.$modal.msgSuccess('图片不能为空')
            return
          }
          if (this.dialogImageUrl.length > 100) {
            this.$modal.msgSuccess('正在上传图片，请稍后')
            return
          }
          const data = this.form
          //考生维护页面 type为0 只维护考生信息
          data.type = 0
          //考生信息
          this.zxmcList.forEach(item => {
            if (item.zxdm == data.zxmc) {
              data.zxmc = item.zxmc
              data.zxdm = item.zxdm
            }
          })
          if (this.form.id != null) {
            updateCandidate(data, this.form.id).then(response => {
              if (response.status === 'success') {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
                schoolClass().then(response => {
                  this.bjdmList = response.data
                })
              } else {
                this.$modal.msgSuccess(response.message)
              }
            })
          } else {
            addCandidate(data).then(response => {
              if (response.status === 'success') {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
                schoolClass().then(response => {
                  this.bjdmList = response.data
                })
              } else {
                this.$modal.msgSuccess(response.message)
              }
            })
          }
        }
      })
    },
    setCandidateList2(records) {
      var j = 0
      this.candidateList2 = new Array(5)
      for (var i = 0; i <= records.length; i = i + 2) {
        if (records[i] == null) {
          break
        }
        const row = {'one': null, 'two': null}
        row.one = records[i]
        row.two = records[i + 1]
        this.candidateList2[j] = row
        j++
      }
    },
    handleExport() {
      //todo 打印未完成
      const selections = this.selections
      console.log(selections)
      // let routeUrl = this.$router.resolve({
      //   path: "/exam/export",
      //   params: {data:selections}
      // });
      this.$router.push({
        path: '/exam/export',
        query: {data: selections}
      })
    },
    resultqymc(value) {
      this.qyList.forEach(info => {
        if (info.v == value) {
          return value = info.n
        }
      })
      return value
    },
    // 覆盖默认的上传行为
    requestUpload() {
    },
    // 上传图片
    uploadZp(file) {
      if (file.type.indexOf('image/') == -1) {
        this.$modal.msgError('文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。')
      } else {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.dialogImageUrl = reader.result
          this.imageFile = file
          let formData = new FormData()
          formData.append('photofile', this.imageFile)
          uploadPhoto(formData).then(response => {
            this.dialogImageUrl = process.env.VUE_APP_BASE_API + response.imgUrl
            this.form.zp = response.imgUrl
            this.$modal.msgSuccess('上传成功')
          })
        }
      }
    },
    zxmcChange(value) {
      this.zxmcList.forEach(item => {
        if (item.zxdm == value) {
          this.form.qy = item.qxdm
        }
      })
    }
  }
}
</script>
